
// 提示
function toast(msg) {
    var html = '<div class="modal fade" id="message" tabindex="-1" role="dialog" aria-hidden="true">' +
        '<div class="modal-dialog modal-dialog-centered" role="document">' +
        '<div class="modal-content">' +
        '<div class="modal-header">' +
        '<h5 class="modal-title">提示</h5>' +
        '<button type="button" class="close" data-dismiss="modal" aria-label="Close">' +
        '<span aria-hidden="true">&times;</span>' +
        '</button>' +
        '</div>' +
        '<div class="modal-body">' + msg + '</div>' +
        '<div class="modal-footer">' +
        '<button type="button" class="btn btn-primary" data-dismiss="modal">确定</button>' +
        '</div>' +
        '</div>' +
        '</div>' +
        '</div>';
    $('body').append(html);
    $('#message').modal('show');
    $('#message').on('hidden.bs.modal', function () {
        $('#message').remove();
    });
}

// 提示并且跳转地址
function toast_tip2(msg, url) {
    var html = '<div class="modal fade" id="message" tabindex="-1" role="dialog" aria-hidden="true">' +
        '<div class="modal-dialog modal-dialog-centered" role="document">' +
        '<div class="modal-content">' +
        '<div class="modal-header">' +
        '<h5 class="modal-title">提示</h5>' +
        '<button type="button" class="close" data-dismiss="modal" aria-label="Close">' +
        '<span aria-hidden="true">&times;</span>' +
        '</button>' +
        '</div>' +
        '<div class="modal-body">' + msg + '</div>' +
        '<div class="modal-footer">' +
        '<button type="button" class="btn btn-primary" data-dismiss="modal">确定</button>' +
        '</div>' +
        '</div>' +
        '</div>' +
        '</div>';
    $('body').append(html);
    $('#message').modal('show');
    $('#message').on('hidden.bs.modal', function () {
        $('#message').remove();
        window.location = url;
    });
}

// 操作提示
function operation_tip() {
    let html = '<div class="modal fade" id="operation" tabindex="-1">' +
        '<div class="modal-dialog modal-dialog-centered">' +
        '<div class="modal-content">' +
        '<div class="modal-header">' +
        '<h5 class="modal-title">提示</h5>' +
        '<button type="button" class="close" data-dismiss="modal">' +
        '<span aria-hidden="true">&times;</span>' +
        '</button>' +
        '</div>' +
        '<div class="modal-body">是否要继续操作？</div>' +
        '<div class="modal-footer">' +
        '<button type="button" class="btn btn-primary" data-dismiss="modal" onclick="parent.window.submit()">确定</button>' +
        '<button type="button" class="btn btn-secondary" data-dismiss="modal">取消</button>' +
        '</div>' +
        '</div>' +
        '</div>' +
        '</div>';
    $('body').append(html);
    $('#operation').modal('show');
    $('#operation').on('hidden.bs.modal', function () {
        $('#operation').remove();
    });
}

// 操作提示2,附带参数
function operation_tip2(id) {
    let html = '<div class="modal fade" id="operation" tabindex="-1">' +
        '<div class="modal-dialog modal-dialog-centered">' +
        '<div class="modal-content">' +
        '<div class="modal-header">' +
        '<h5 class="modal-title">提示</h5>' +
        '<button type="button" class="close" data-dismiss="modal">' +
        '<span aria-hidden="true">&times;</span>' +
        '</button>' +
        '</div>' +
        '<div class="modal-body">是否要继续操作？</div>' +
        '<div class="modal-footer">' +
        '<button type="button" class="btn btn-primary" data-dismiss="modal" onclick="parent.window.submit('+id+')">确定</button>' +
        '<button type="button" class="btn btn-secondary" data-dismiss="modal">取消</button>' +
        '</div>' +
        '</div>' +
        '</div>' +
        '</div>';
    $('body').append(html);
    $('#operation').modal('show');
    $('#operation').on('hidden.bs.modal', function () {
        $('#operation').remove();
    });
}

//设置菜单激活状态
!function () {
    let menuBtns = document.querySelectorAll('#sidebar-menu a');
    let pathName;

    let str = window.location.href.replace(window.location.origin, '');

    if (str.indexOf('?') <= '0') {
        pathName = str
    }

    if (str.indexOf('?') >= '0') {
        pathName = str.slice(0, str.indexOf('?'))
    }

    /*
    if ( str.indexOf('/',str.indexOf('/')+6) >= 15){
        pathName = str.slice(0,str.indexOf('/',str.indexOf('/')+6))
    }
    */

    for (let i = 0; i < menuBtns.length; i++) {
        let ele = menuBtns[i];
        let href = ele.getAttribute('href').replace(window.location.origin, '');

        if (href == pathName) {
            ele.parentNode.className = ele.parentNode.className + 'mm-active';
        } else {
            ele.parentNode.className = ele.parentNode.className.replace('mm-active', '');
        }
    }
}();

//设置后台菜单激活状态
/*!function () {
    let menuBtns = document.querySelectorAll('#sidebar-admin-menu a');
    let pathName;

    let str = window.location.href.replace(window.location.origin, '');

    if (str.indexOf('?') <= '0') {
        pathName = str
    }

    if (str.indexOf('?') >= '0') {
        pathName = str.slice(0, str.indexOf('?'))
    }

    if ( str.indexOf('/',str.indexOf('/')+12) == 12){
        pathName = str.slice(0,str.indexOf('/',str.indexOf('/')+12))
    }

    for (let i = 0; i < menuBtns.length; i++) {
        let ele = menuBtns[i];
        let href = ele.getAttribute('href').replace(window.location.origin, '');

        if (href == pathName) {
            ele.parentNode.className = ele.parentNode.className + 'mm-active';
        } else {
            ele.parentNode.className = ele.parentNode.className.replace('mm-active', '');
        }
    }
}();*/

// 获取视图宽度
function getViewportWidth() {
    return Math.max(document.documentElement.clientWidth, window.innerWidth || 0);
}

//返回视图名称-sidebar-compact-desktop
function getViewportName() {

    var viewportWidth = getViewportWidth();

    if (viewportWidth < 576) {
        return 'xs';
    }
    else if (viewportWidth >= 576 && viewportWidth < 768) {
        return 'sm';
    }
    else if (viewportWidth >= 768 && viewportWidth < 992) {
        return 'md';
    }
    else if (viewportWidth >= 992 && viewportWidth < 1200) {
        return 'lg';
    }
    else {
        return 'xl';
    }
}

/**
 * 发送请求
 * @param method
 * @param url
 * @param data
 * @param success
 */
$.ajaxSetup({
    headers : {
        'X-CSRF-TOKEN' : $("meta[name='csrf-token']").attr('content')
    }
});
function sendRequest(method, url, data, successFun) {
    $.ajax({
        //请求方式
        type : method,
        //请求的媒体类型
        contentType: "application/json;charset=UTF-8",
        //请求地址
        url : url,
        //数据，json字符串
        data : JSON.stringify(data),
        dataType: 'json',
        //请求成功
        success : function(result) {
            if (result.success === 'false') {
                errorMsg(result.message)
                return;
            }
            successFun(result)
        },
        //请求失败，包含具体的错误信息
        error : function(e){
            // 登录
            if (e.status === 410) {
                checkLogin();
                return;
            }
            // 绑定手机
            if (e.status === 420) {
                openBindMobilePage();
                return;
            }
            errorMsg(JSON.parse(e.responseText).message)
        }
    });
}

function successMsg(msg, fun) {
    layer.open({content: msg, icon: 1}, fun);
}

function errorMsg(msg, fun) {
    layer.open({content: msg, icon: 5}, fun);
}

/**
 * 判断是否登录
 */
function checkLogin() {
    $.ajax({
        //请求方式
        type : 'GET',
        //请求的媒体类型
        contentType: "application/json;charset=UTF-8",
        //请求地址
        url : '/isLogin',
        //数据，json字符串
        data : '',
        dataType: 'json',
        //请求成功
        success : function(result) {
            if (result.success === 'false') {
                openLoginPage()
            }
        },
        //请求失败，包含具体的错误信息
        error : function(e){
            openLoginPage()
        }
    });
}

function getQrCode(string) {
    jQuery('#qrcode').qrcode({
        render: "canvas", //也可以替换为table
        width: 260,
        height: 260,
        text: string
    });
}

/**
 * 登录二维码页面
 */
let loginPageIndex = 0;
let timeController = 0
function openLoginPage() {
    sendRequest('GET', '/wechat/code', {}, function (res) {
        loginPageIndex = layer.open({
            type: 1,
            title: '登录',
            content: `
            <div class="wx-login-msg">请使用微信扫码登录</div>
            <div id="qrcode"></div>
            <!--<div class="login-mobile-btn" onclick="goMobileLogin()">短信验证码登录</div>-->`,
            area: ['330px', '420px'],
            cancel: function(index, layero){
                if(timeController){
                    clearInterval(timeController);
                }
            },
            end: function(index, layero){
                if(timeController){
                    clearInterval(timeController);
                }
            }
        })
        getQrCode(res.data.url)
        getLoginStatus(res.key)
    })
}

function getIndexLoginCode() {
    sendRequest('GET', '/wechat/code', {}, function (res) {
        document.getElementById('index-qrcode').innerHTML= ""
        jQuery('#index-qrcode').qrcode({
            render: "canvas", //也可以替换为table
            width: 140,
            height: 140,
            text: res.data.url
        });
        getLoginStatus(res.key)
    })
}

function getLoginStatus(key) {
    timeController =
    setInterval(function () {
        $.ajax({
            //请求方式
            type : 'GET',
            //请求的媒体类型
            contentType: "application/json;charset=UTF-8",
            //请求地址
            url : '/getLoginStatus/' + key,
            //数据，json字符串
            data : '',
            dataType: 'json',
            //请求成功
            success : function(result) {
                if (result.success === 'true') {
                    successMsg('登录成功')
                    layer.close(loginPageIndex)
                    clearInterval(timeController);
                    // 判断是否需要绑定手机
                    sendRequest('GET', '/needBindMobile', {}, function (res) {
                        console.log(res)
                        if (res.data === 1) {
                            openBindMobilePage();
                        }
                        location.href = '/userCenter'
                    })
                }
                if (result.success === 'reload') {
                    // 重新获取二维码
                    if (document.getElementById('index-qrcode')) {
                        getIndexLoginCode()
                    }
                }
            },
            //请求失败，包含具体的错误信息
            error : function(e){

            }
        });
    }, 2500)
}

/**
 * 绑定手机页面
 */
function openBindMobilePage() {
    layer.open({
        type: 2,
        title: "绑定手机",
        content: "/bindMobilePage",
        area: ['520px', '300px']
    })
}
